package com.example.springboot.service;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author yuwl
 * @description
 * @since 2023-12-22 14:48
 */
//@Service
public class DistributedLockService {

//    @Autowired
    private RedissonClient redissonClient;

    private RLock lock;

    public void setRedissonClient(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    public boolean acquireLock(long waitTime, long leaseTime) {
        String lockKey = "myLock";
        lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    public void releaseLock() {
        lock.unlock();
        System.out.println("释放锁成功");
    }

    public void executeWithLock() {
        if (acquireLock(10, 60)) { // 尝试获取锁，最多等待 10 秒，持有锁 60 秒
            try {
                // 成功获取到锁，执行业务逻辑
                System.out.println("执行业务逻辑");
                // 模拟业务执行时间
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                // 处理异常
                e.printStackTrace();
            } finally {
                releaseLock();
            }
        } else {
            // 获取锁超时，执行其他逻辑
            System.out.println("获取锁超时");
        }
    }
}
